package com.cqrt.aop;

import cn.hutool.core.collection.CollUtil;
import com.cqrt.constant.RTErrorCodeEnum;
import com.cqrt.constant.RTPlmConstant;
import com.cqrt.mapper.BaseLinePlanExpandMapper;
import com.cqrt.mapper.RTProjectsTemplateMapper;
import com.hustcad.plm.rpm.model.dto.plan.TyppmBaselinePlanCreateDTO;
import com.hustcad.plm.rpm.service.plan.TyppmBaselinePlanService;
import com.ty.ppm.model.entity.plan.BaselinePlan;
import com.ty.ppm.service.mapper.plan.BaselinePlanMapper;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
import java.math.BigInteger;
import java.util.List;


/**
 * @Author：lotus
 * @DATE: 2025/7/2 21:01
 */



@Aspect
@Component
@Slf4j
@Transactional
public class CreateBasicAOP {

    @Resource
    private RTProjectsTemplateMapper rtProjectsTemplateMapper;
    @Resource
    private TyppmBaselinePlanService baselinePlanService;
    @Resource
    private BaseLinePlanExpandMapper baseLinePlanExpandMapper;

    //项目启动时创建初始计划基线
    @Before("execution(* com.hustcad.plm.rpm.project.service.impl.TyppmProjectServiceImpl.setProjectStateStarted(..))")
    public void getTemplateLinkJobTestAOP(JoinPoint joinPoint)  {

        List<String> list  = (List<String>) joinPoint.getArgs()[0];
        BigInteger planId = rtProjectsTemplateMapper.getPlanById(list.get(0));
        String oid = planId.toString();
        TyppmBaselinePlanCreateDTO baselinePlanCreateDTO = new TyppmBaselinePlanCreateDTO();
        baselinePlanCreateDTO.setPlanOid(oid);
        baselinePlanCreateDTO.setBaselineName(RTPlmConstant.INITIAL_PLAN);
        this.baselinePlanService.createPlanBaseline(baselinePlanCreateDTO);


    }


    //禁止创建重名基线
    @Before("execution(* com.hustcad.plm.rpm.service.impl.plan.TyppmBaselinePlanServiceImpl.createPlanBaseline(..))")
    public void createBasicCreateNameAOP(JoinPoint joinPoint)  {

        TyppmBaselinePlanCreateDTO typpmBaselinePlanCreateDTO = (TyppmBaselinePlanCreateDTO)joinPoint.getArgs()[0];

        BaselinePlan baselinePlan = new BaselinePlan();
        baselinePlan.setBaselineName(typpmBaselinePlanCreateDTO.getBaselineName());
        baselinePlan.setContaineroid(new BigInteger(typpmBaselinePlanCreateDTO.getPlanOid()));
        List<BaselinePlan> baselinePlans = baseLinePlanExpandMapper.selectBaselinePlanByName(baselinePlan);

        if (CollUtil.isNotEmpty(baselinePlans)) {
            throw RTErrorCodeEnum.FORBID_REPETITION_NAME.getException("禁止创建重名基线");
        }

    }
}
